package com.xkw.autocode.web.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xkw.autocode.base.BaseController;
import com.xkw.autocode.enums.AdminTypeEnum;
import com.xkw.autocode.vo.UserConfigVo;
import com.xkw.autocode.web.databaseconfig.DatabaseConfigUrlUtil;
import com.xkw.autocode.web.datatypeconfig.DataTypeConfigUrlUtil;
import com.xkw.autocode.web.templateconfig.TemplateConfigUrlUtil;
import com.xkw.autocode.web.templateconfigdetail.TemplateConfigDetailUrlUtil;
import com.xkw.autocode.web.userconfig.UserConfigUrlUtil;

/**
 * 权限拦截器
 * 
 * @author xiangkaiwei
 *
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

	private static final String NO_FILTER = "/login.htm";

	private static final String NO_AUTHORITY = "/noauth.htm";

	public static final String REQUEST_HEAD = "x-requested-with";

	// 不需要登录访问的链接
	private static List<String> openRights = new ArrayList<>();

	// 需要管理员才能访问的链接
	private static List<String> adminRights = new ArrayList<>();
	static {
		openRights.add("/doLogin.htm");
		openRights.add(NO_FILTER);
		openRights.add("/loginCode.htm");
		openRights.add("/doLogout.htm");
		openRights.add("/404.htm");

		adminRights.add(UserConfigUrlUtil.DO_ADD);
		adminRights.add(UserConfigUrlUtil.TO_MODIFY);
		adminRights.add(UserConfigUrlUtil.DO_MODIFY);
		adminRights.add(UserConfigUrlUtil.DO_DELETE);

		adminRights.add(DatabaseConfigUrlUtil.DO_ADD);
		adminRights.add(DatabaseConfigUrlUtil.TO_MODIFY);
		adminRights.add(DatabaseConfigUrlUtil.DO_MODIFY);
		adminRights.add(DatabaseConfigUrlUtil.DO_DELETE);

		adminRights.add(DataTypeConfigUrlUtil.DO_ADD);
		adminRights.add(DataTypeConfigUrlUtil.TO_MODIFY);
		adminRights.add(DataTypeConfigUrlUtil.DO_MODIFY);
		adminRights.add(DataTypeConfigUrlUtil.DO_DELETE);

		adminRights.add(TemplateConfigUrlUtil.DO_ADD);
		adminRights.add(TemplateConfigUrlUtil.TO_MODIFY);
		adminRights.add(TemplateConfigUrlUtil.DO_MODIFY);
		adminRights.add(TemplateConfigUrlUtil.DO_DELETE);

		adminRights.add(TemplateConfigDetailUrlUtil.DO_ADD);
		adminRights.add(TemplateConfigDetailUrlUtil.TO_MODIFY);
		adminRights.add(TemplateConfigDetailUrlUtil.DO_MODIFY);
		adminRights.add(TemplateConfigDetailUrlUtil.DO_DELETE);
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String uri = request.getRequestURI();

		String contextPath = request.getContextPath();

		String tmpUri = uri.replace(contextPath, "");

		if (openRights.contains(tmpUri)) {
			return true;
		}

		UserConfigVo userConfigVo = (UserConfigVo) request.getSession().getAttribute(BaseController.SESSION_USER_KEY);
		if (userConfigVo == null) {
			logger.info("登录过期，URL={}", uri);
			sendRedirect(request, response, "timeout", contextPath + NO_FILTER);
			return false;
		}

		if (adminRights.contains(tmpUri) && AdminTypeEnum.ADMIN.getValue() != userConfigVo.getUserType()) {

			logger.info("无权限访问，userName={},URL={}", userConfigVo.getUserName(), uri);

			sendRedirect(request, response, "noauth", contextPath + NO_AUTHORITY);
			return false;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		//
	}

	private void sendRedirect(HttpServletRequest request, HttpServletResponse response, String key, String url)
			throws IOException {

		// 判断ajax请求,如果是ajax请求响应头会有，x-requested-with
		if (request.getHeader(REQUEST_HEAD) != null
				&& request.getHeader(REQUEST_HEAD).equalsIgnoreCase("XMLHttpRequest")) {

			// 在响应头设置session状态
			response.setHeader("sessionstatus", key);
			response.getWriter().write(key);
		} else {
			// 跳转到登录页面
			response.setStatus(302);// 或者303,兼容http1.1
			response.setHeader("location", url);
		}

	}
}